/*
 * @description: 动态路由
 * @Author: Islands
 * @Date: 2024-06-17 18:48:08
 * @LastEditTime: 2024-06-20 18:54:05
 */
// import Cookies from 'js-cookie'
import router from '@/plugins/router/index';
import { storeToRefs } from "pinia";
import { useStore } from '@/plugins/pinia/index';
import NProgress from 'nprogress';  //进度条组件
import 'nprogress/nprogress.css';   //进度条组件样式
import { WHITELIST, LOGIN_REDIRECT, HOME } from '@/constant/white'
import { IUserInfo, ILoginResult } from '@/api/types/login.d';
import { GlobalEnum } from '@/enums/index';

/**
 * @description: 1.前置守卫
 * @author: Islands
 * @param {*} to 即将要进入的目标
 * @param {any} from 当前导航正要离开的路由
 * @param {any} next    路由的控制参数，常用的有next(true)和next(false)
 * @return {*}
 */
router.beforeEach(async (to: any, from: any, next: any) => {
    NProgress.start();
    const { userInfo } = storeToRefs(useStore());
    try {
        const { getToken, getUserInfo, getRoutes } = useStore();
        //确认token是否存在
        let hasToken = sessionStorage.getItem(GlobalEnum.AUTHORIZE)
        if (null == hasToken) {
            let accessToken: any = await getToken();
            if (accessToken !== null) {
                next({ ...to, replace: true });
            } else {
                WHITELIST.includes(to.path) ? next() : next({ path: LOGIN_REDIRECT, query: { redirect: to.meta.redirect } })
            }

        } else {
            // if已登录还在访问 ‘/login’ 则直接进入首页,else 根据角色权限加载动态路由
            if (to.path === LOGIN_REDIRECT) {
                next({ path: HOME });
            } else {
                let rolesStore = userInfo.value.roles
                if (rolesStore && rolesStore.length > 0) {
                    // 未匹配到任何路由，跳转404
                    to.matched.length === 0 ? from.name ? next({ name: from.name }) : next("/404") : next();
                } else {
                    let { roles }: IUserInfo = await getUserInfo();
                    let accessedRoutes: any = await getRoutes(roles);
                    accessedRoutes.forEach((route: any) => {
                        router.addRoute(route);
                    });
                    next({ ...to, replace: true });
                }

            }
        }
    } catch (e: any) {
        console.log("路由请求异常:", e);
        next(LOGIN_REDIRECT)
    }
});
/**
 * @description: 2.全局后置守卫
 * @author: Islands
 * @param {any} to
 * @param {any} from
 * @return {*}
 */
router.afterEach((to: any, from: any) => {
    //设置跳转路由后页面的标题
    document.title = (to.meta.title ? to.meta.title : 'Saa平台');
    NProgress.done();

});

